package com.atguigu.tingshu.account.api;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.GuiguLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户账户管理")
@RestController
@RequestMapping("api/account/userAccount")
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountApiController {

	@Autowired
	private UserAccountService userAccountService;

	@Operation(summary = "保存用户账户")
	@PostMapping("saveAccount/{userId}")
	public Result saveAccount(@PathVariable Long userId){
		this.userAccountService.saveAccount(userId);
		return Result.ok();
	}

	///api/account/userAccount/getAvailableAmount
	@GuiguLogin
	@Operation(summary = "查询用户账户金额")
	@GetMapping("getAvailableAmount")
	public Result getAvailableAmount(){
		UserAccount userAccount = userAccountService.getOne(Wrappers
				.lambdaQuery(UserAccount.class)
				.eq(UserAccount::getUserId, AuthContextHolder.getUserId())
				.select(UserAccount::getAvailableAmount));
		if(userAccount==null){
			throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
		}
		return Result.ok(userAccount.getAvailableAmount());
	}

	@Operation(summary = "内部接口：校验并扣除账户余额、保存账户交易流水")
	@GuiguLogin
	@PostMapping("checkAndDeduction")
	public Result<Boolean> checkAndDeduction(@RequestBody AccountLockVo accountLockVo){
		boolean flag = userAccountService.checkAndDeduction(accountLockVo);
		return Result.ok(flag);
	}
}

